package com.hk.service.impl;

import com.hk.dao.OnlineMessageDao;
import com.hk.model.Document;
import com.hk.model.OnlineMessage;
import com.hk.service.IOnlineMessageService;
import com.hk.utils.Io;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: KangWang
 * Date: 2021/5/20 16:09
 * State：在线留言业务逻辑层
 */
public class OnlineMessageServiceImpl implements IOnlineMessageService {


    List<OnlineMessage> onlineMessageList = null;
    //        设定一个默认变量为0，用于检测是否新增成功
    int size = 0;

    @Override
    public void saveMessage(String path, OnlineMessage onlineMessage) {
        OnlineMessageDao onlineMessageDao = new OnlineMessageDao();
        onlineMessageList = onlineMessageDao.saveMessage(onlineMessage);
//      1、存储路径  2、文件夹 3、文件
        Document document = new Document(path,"OnlineMessage", "OnlineMessage.txt");
//        检索存储路径和文件夹或文件是否存在，并写入书局
        writeData(onlineMessageList,document);
//        读取数据
        onlineMessageList = (List<OnlineMessage>) readData(document);
        if (onlineMessageList.size() > size) {
            System.out.println(
                    "新增留言：" +
                            "标题：" + onlineMessage.getMessageTitle() +
                            "邮箱：" + onlineMessage.getMessageEmail() +
                            "内容：" + onlineMessage.getMessageContent()
            );
            System.out.println("所有留言:"+onlineMessageList);
            size = onlineMessageList.size();
        } else {
            System.out.println("留言失败");
        }
    }

    @Override
    public List<?> readData(Document document) {
        //    根据该对象内多少属性进行转化划分
        final int count = 4;
        onlineMessageList = new ArrayList<>();
        List<String> list = Io.readData(document);
        for (int i = 0; i < list.size(); i=i+count) {
            OnlineMessage onlineMessage = new OnlineMessage(
                Integer.parseInt(list.get(i)),
                list.get(i+1),
                list.get(i+2),
                list.get(i+3)
            );
            onlineMessageList.add(onlineMessage);
        }
        return onlineMessageList;
    }

    @Override
    public void writeData(List<?> list, Document document) {
        onlineMessageList = (List<OnlineMessage>) list;
        List<String> list1 = new ArrayList<>();
        for (OnlineMessage onlineMessage : onlineMessageList) {
            list1.add(String.valueOf(onlineMessage.getMessageId()));
            list1.add(onlineMessage.getMessageTitle());
            list1.add(onlineMessage.getMessageEmail());
            list1.add(onlineMessage.getMessageContent());
        }
        Io.writeData(list1,document);

    }
}
